import { FC, useState, useEffect } from 'react'
import {
  ProTable,
  ProColumns,
  ModalForm,
  ProForm,
  ProFormDateTimePicker,
  ProFormSelect,
  ProFormText
} from '@ant-design/pro-components'
import useRequest from '@ahooksjs/use-request'
import type { ActionType } from '@ant-design/pro-components'
import { PlusOutlined, UploadOutlined, DatabaseTwoTone } from '@ant-design/icons'
import { useRef } from 'react'
import {
  Button,
  PageHeader,
  Input,
  message,
  Form,
  Popconfirm,
  Upload,
  UploadProps,
  Col,
  Row
} from 'antd'
import { history } from 'umi'
import styles from './index.less'
import { getAllCourseData } from '@/services/courseManagement/types'
import { useDispatch } from 'dva'
import { ACTIONS } from '@/models'
import courseMagServices from '@/services/courseManagement/index'

const courseMag: FC = () => {
  const actionRef = useRef<ActionType>()
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const formData = new FormData()
  const [isCreateModal, setIsCreateModal] = useState(false)
  const [isUpdateModal, setIsUpdateModal] = useState(false)
  const [isOpen, setIsOpen] = useState(false)
  const [pageNum, setPageNumber] = useState(1)
  const [searchText, setSearchText] = useState('')
  const [courseList, setCourseList] = useState<getAllCourseData[]>()
  const [fileList, setFileList] = useState([] as any)
  const [courseId, setCourseId] = useState('')
  const [courseData, setCoureseData] = useState<getAllCourseData>()
  const [update, setUpdate] = useState(0)
  const pageSize = 10
  //开始录制
  const { run: startRecord } = useRequest(courseMagServices.startRecord, {
    manual: true,
    onSuccess: () => {
      message.success('开始录制......')
    }
  })
  //停止录制
  const { run: stopRecord } = useRequest(courseMagServices.stopRecord, {
    manual: true,
    onSuccess: () => {
      message.success('已暂停录制！')
    }
  })
  //分析
  const { run: runAnalyze } = useRequest(courseMagServices.analyzeRecord, {
    manual: true,
    onSuccess: () => {
      message.success('分析完成！')
    }
  })
  //获取列表
  const { data: allcourseList, run: getAllCourse } = useRequest(courseMagServices.getAllCourse, {
    manual: true,
    onSuccess: (res) => {
      setCourseList(res.records)
    }
  })
  //删除课程
  const { run: deleteCourse } = useRequest(courseMagServices.deleteCourse, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功！')
      setUpdate(update + 1)
    }
  })
  //新建课程
  const { run: createCourse } = useRequest(courseMagServices.createCourse, {
    manual: true,
    onSuccess: () => {
      message.success('新建成功！')
      setIsCreateModal(false)
      setUpdate(update + 1)
      setIsOpen(false)
    }
  })
  //上传文件
  const { run: uploadFile } = useRequest(courseMagServices.uploadFile, {
    manual: true,
    onSuccess: () => {
      fileList.length = 0
    }
  })
  //更新课程
  const { run: updateCourse } = useRequest(courseMagServices.updateCourse, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功！')
      setIsUpdateModal(false)
      setIsOpen(false)
      setUpdate(update + 1)
    }
  })
  //加载请求
  useEffect(() => {
    getAllCourse({ description: searchText, page: pageNum, pageSize })
  }, [pageNum, searchText, update])
  //表头
  const columns: ProColumns<getAllCourseData>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 48,
      align: 'center'
    },
    {
      title: '课程名称',
      dataIndex: 'name',
      align: 'center',
      renderFormItem: (_, { defaultRender }) => {
        return defaultRender(_)
      }
    },
    {
      title: '课程状态',
      dataIndex: 'status',
      valueType: 'select',
      align: 'center',
      valueEnum: {
        all: { text: '全部', status: 'Default' },
        open: {
          text: '未解决',
          status: 'Error'
        },
        closed: {
          text: '已解决',
          status: 'Success'
        }
      }
    },
    {
      title: '教师',
      dataIndex: 'teacherName',
      align: 'center'
    },
    {
      title: '班级',
      dataIndex: 'className',
      align: 'center'
    },
    {
      title: '课程时间',
      valueType: 'dateTime',
      dataIndex: 'startTime',
      align: 'center'
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (text, record, index, action) => [
        <a
          onClick={() => {
            dispatch({
              type: ACTIONS.saveInfo.courseInfo,
              payload: {
                courseId: record.id,
                courseName: record.name
              },
              callback: (data: any) => {
                history.push('./studentManagement')
              }
            })
          }}
          key="detail"
        >
          查看
        </a>,
        <a
          key="editable"
          onClick={() => {
            setIsUpdateModal(true)
            setIsOpen(true)
            setCoureseData({ ...record })
            setCourseId(record.id)
          }}
        >
          修改
        </a>,
        <Popconfirm
          key="删除"
          title={`是否确认删除【${record.name}】这门课？`}
          onConfirm={() => {
            deleteCourse({ id: record.id })
          }}
        >
          <a>删除</a>
        </Popconfirm>
      ]
    },
    {
      title: '课程视频（录制）',
      valueType: 'option',
      align: 'center',
      render: (text, record, index, action) => [
        <a key={'start'} style={{ color: 'red' }} onClick={() => startRecord({ id: record.id })}>
          开始
        </a>,
        <a key={'stop'} style={{ color: 'red' }} onClick={() => stopRecord({ id: record.id })}>
          停止
        </a>,
        <a key={'anlyse'} style={{ color: 'red' }} onClick={() => runAnalyze({ id: record.id })}>
          分析
        </a>
      ]
    }
  ]
  //搜索
  const onSearch = (value: string) => {
    setSearchText(value)
  }
  //上传文件
  const props: UploadProps = {
    maxCount: 1,
    beforeUpload: (file) => {
      const size = file.size / 1024 / 1024 / 1024
      if (size > 2) {
        message.warning('文件大小超过2G！请重新上传！')
        return false
      } else {
        setFileList(file)
        return true
      }
    },
    customRequest: (file) => {
      formData.append('type', 'course')
      formData.append('file', file.file)
    }
    // fileList
  }
  //提交
  const onSummit = (values: any) => {
    if (isCreateModal) {
      createCourse({ ...values })
    } else {
      const { name, teacherName, startTime, status, className } = values
      updateCourse({ id: courseData?.id, name, teacherName, className, status, startTime })
    }
    if (fileList.length != 0) {
      uploadFile(formData as any)
    }
  }
  return (
    <div className={styles.ContrntStyle}>
      <div className={styles.header}>
        <PageHeader
          backIcon={<DatabaseTwoTone />}
          onBack={() => {
            history.push('./courseManagement')
          }}
          title="课程管理"
          extra={[
            <Input.Search placeholder="请输入：名称|状态|教师|班级" onSearch={onSearch} />,
            <Button
              type="primary"
              onClick={() => {
                setIsCreateModal(true)
                setIsOpen(true)
              }}
            >
              <PlusOutlined />
              新建课程
            </Button>
          ]}
        ></PageHeader>
      </div>
      <div className={styles.showTable}>
        {' '}
        <ProTable<getAllCourseData>
          headerTitle={`课程总数：${allcourseList?.total}`}
          cardBordered
          form={{
            // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                  created_at: [values.startTime, values.endTime]
                }
              }
              return values
            }
          }}
          editable={{ type: 'single', onSave: async () => {} }}
          actionRef={actionRef}
          columns={columns}
          dataSource={courseList}
          dateFormatter="string"
          search={false}
          pagination={{
            total: allcourseList?.total,
            pageSize: allcourseList?.size,
            onChange: (pageNum) => {
              setPageNumber(pageNum)
            }
          }}
        ></ProTable>
      </div>
      <div className={styles.createModal}>
        <ModalForm
          layout="horizontal"
          open={isOpen}
          title={isCreateModal ? '新建课程' : '修改课程'}
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setIsCreateModal(false)
              setIsUpdateModal(false)
              setIsOpen(false)
            }
          }}
          form={form}
          autoFocusFirstInput
          onFinish={async (values) => onSummit(values)}
        >
          <ProForm.Group title="基本信息">
            <ProFormText
              name={'name'}
              rules={[{ required: true, message: '课程名称不能为空！' }]}
              label="课程名称"
              initialValue={isUpdateModal ? courseData?.name : ''}
            ></ProFormText>
            <ProFormText
              name={'teacherName'}
              rules={[{ required: true, message: '教师名称不能为空！' }]}
              label="教师名称"
              initialValue={isUpdateModal ? courseData?.teacherName : ''}
            ></ProFormText>
            <ProFormText
              name={'className'}
              rules={[{ required: true, message: '班级名称不能为空！' }]}
              label="班级名称"
              placeholder={'例：电信二班'}
              initialValue={isUpdateModal ? courseData?.className : ''}
            ></ProFormText>
          </ProForm.Group>
          <ProForm.Group title="课程状态">
            <ProFormSelect
              rules={[{ required: true, message: '不能为空！' }]}
              initialValue={isUpdateModal ? courseData?.status : ''}
              name={'status'}
              label="请在以下选择"
              valueEnum={{
                进行中: '进行中',
                未开始: '未开始',
                已完成: '已完成'
              }}
            ></ProFormSelect>
          </ProForm.Group>
          <ProForm.Group title="开始时间">
            <ProFormDateTimePicker
              rules={[{ required: true, message: '不能为空！' }]}
              initialValue={isUpdateModal ? courseData?.startTime : null}
              name={'startTime'}
              label="日期时间"
              fieldProps={{
                format: (value) => value.format('YYYY-MM-DD HH:MM:ss')
              }}
            ></ProFormDateTimePicker>
          </ProForm.Group>
          <ProForm.Group title="上传课程视频" direction="vertical">
            <Row>
              {' '}
              <Col>每次只能上传一个视频且大小不能超过2G！</Col>
              <Col>{isUpdateModal ? '(若要更新视频则再次上传)' : ''}</Col>
            </Row>
            <Row>
              {' '}
              <Col span={'100%'}>
                {' '}
                <Upload {...props}>
                  <Button>
                    <UploadOutlined />
                    点击上传
                  </Button>
                </Upload>
              </Col>
              {/* <Col><Button onClick={() => {history.push('./camera') }}>点击录制</Button></Col> */}
            </Row>
          </ProForm.Group>
        </ModalForm>
      </div>
    </div>
  )
}

export default courseMag
